package com.alexgaoyh.draging.gridster;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.alexgaoyh.draging.entity.GridsterEntity;

public class InitServlet extends HttpServlet {
	
	/* var widgets = [ 
    [ '<li id="1">content-1(1,2,1,1)</li>', 1, 2, 1, 1 ], 
    [ '<li id="2">content-2(3,2,2,1)</li>', 3, 2, 2, 1 ],
	[ '<li id="3">content-3(3,2,5,1)</li>', 3, 2, 5, 1 ], 
	[ '<li id="4">content-4(3,1,8,1)</li>', 3, 1, 8, 1 ],
	[ '<li id="5">content-5(1,1,11,1)</li>', 1, 1, 11, 1 ],
	[ '<li id="6">content-6(3,1,8,2)</li>', 3, 1, 8, 2 ],
	[ '<li id="7">content-7(1,1,11,2)</li>', 1, 1, 11, 2 ], 
	[ '<li id="8">content-8(3,1,1,3)</li>', 3, 1, 1, 3 ],
	[ '<li id="9">content-9(1,1,4,3)</li>', 1, 1, 4, 3 ], 
	[ '<li id="10">content-10(4,1,5,3)</li>', 4, 1, 5, 3 ],
	[ '<li id="11">content-11(3,1,9,3)</li>', 3, 1, 9, 3 ] 
]; */
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		List<GridsterEntity> list = new ArrayList<GridsterEntity>();
		
		list.add(new GridsterEntity("<li id=\"1\">content-1(1,2,1,1)</li>", 1, 2, 1, 1));
		list.add(new GridsterEntity("<li id=\"2\">content-2(3,2,2,1)</li>", 3, 2, 2, 1));
		list.add(new GridsterEntity("<li id=\"3\">content-3(3,2,5,1)</li>", 3, 2, 5, 1));
		
		req.setAttribute("widgets", toJSon(list));
		
		RequestDispatcher rd = req.getRequestDispatcher("/gridster/adding-widgets-dynamically.jsp");
		
		rd.forward(req,resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		List<GridsterEntity> list = new ArrayList<GridsterEntity>();
		
		list.add(new GridsterEntity("<li id=\"1\">content-1(1,2,1,1)</li>", 1, 2, 1, 1));
		list.add(new GridsterEntity("<li id=\"2\">content-2(3,2,2,1)</li>", 3, 2, 2, 1));
		list.add(new GridsterEntity("<li id=\"3\">content-3(3,2,5,1)</li>", 3, 2, 5, 1));
		
		req.setAttribute("widgets", toJSon(list));
		
		RequestDispatcher rd = req.getRequestDispatcher("/gridster/adding-widgets-dynamically.jsp");
		
		rd.forward(req,resp);
		
	}
	
	private static String toJSon(Object object) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
